//
//  ViewController.m
//  获得手机通讯录
//
//  Created by hu on 16/8/1.
//  Copyright © 2016年 hu. All rights reserved.
//

#import "ViewController.h"
#import "TTTAttributedLabel.h"
#import "HUContactsManager.h"

static const NSString* url = @"const";

@interface ViewController ()<TTTAttributedLabelDelegate>

@property (nonatomic, strong) HUContactsManager* manager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TTTAttributedLabel* label = [[TTTAttributedLabel alloc]initWithFrame:CGRectZero];
    label.center = self.view.center;
    label.bounds = CGRectMake(0, 0, self.view.frame.size.width-20, 0);

    label.numberOfLines = 0;
    label.enabledTextCheckingTypes = NSTextCheckingTypeLink; // Automatically detect links when the label text is subsequently changed
    label.delegate = self; // Delegate methods are called when the user taps on a link (see `TTTAttributedLabelDelegate` protocol)
    
    label.text = @"点击 me 获得手机通讯录! (https://获得手机通讯录权限)"; // Repository URL will be automatically detected and linked
    [label sizeToFit];
    NSRange range = [label.text rangeOfString:@"me"];
    [label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring

    
    [self.view addSubview:label];
    
    self.manager = [HUContactsManager shareInstance];
    __weak __typeof (&*self)weakSelf = self ;
    self.manager.failAllowContracts = ^(){

        [weakSelf showError];
    };
    
    
    
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    [self.manager requestContactsComplete:^(NSArray<HUContractModel *> * array) {
        for (HUContractModel* model in array ) {
            NSLog(@"name ---- %@",model.nameObject.name);
            NSArray* phoneArray = model.phoneObject;
            for (HUContactPhoneObject* phone in phoneArray) {
                NSString* phoneStr = [phone.phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
                phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"+86" withString:@""];
                NSLog(@"phone ---- %@",phoneStr);
            }
            
        }
    }];
}

- (void)showError {
    UIAlertController* controller = [UIAlertController alertControllerWithTitle:@"" message:@"请在设置中允许获得通讯录权限" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* cancel         = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [controller addAction:cancel];
    [self presentViewController:controller animated:YES completion:nil];
    NSLog(@"获得通讯录失败");
}
@end
